import axios from 'axios'
import router from '../router'

// console.log('import.meta.env', import.meta.env)
// axios.defaults.baseURL = import.meta.env.MODE == 'development' ? 'http://192.168.110.235:8098/user-api' : '//backend-api-01.newbee.ltd/api/v1'
//  axios.defaults.withCredentials = true
//  axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'

axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL
// axios.defaults.headers['boss-token'] = localStorage.getItem('token') || ''
// axios.defaults.headers['lang'] = localStorage.getItem('lang') || 'zh'
axios.defaults.headers.post['Content-Type'] = 'application/json'

axios.interceptors.request.use(config => {
  config.headers['boss-token'] = localStorage.getItem('token') || ''
  config.headers['lang'] = localStorage.getItem('lang') || 'zh'
  return config
})

axios.interceptors.response.use(res => {
  if(res.data instanceof Blob){
    return res.data
  }
  if (res.data.code == 200) {
    return res.data
  } else if (res.code == 200) {
    return res
  } else if (res.data.code == 401) {
    ElMessage.error(res.data.msg||res.msg)
    setTimeout(() => {
      router.replace({ path: `/login` })
    }, 500)
  } else {
    ElMessage.error(res.data.msg)
  }
}, err => {
  // 请求出现错误时回调
  return Promise.reject(err)
})

export default axios
